import getUserTempId from '@/utils/userTempId';
import { getUserInfo, userLogin, userLogout } from '@/api';

export default {
  namespaced: true,
  state: {
    userTempId: getUserTempId(),
    token: localStorage.getItem('token'),
    userinfo: {},
  },
  getters: {
    userinfo: (state) => {
      return state.userinfo;
    },
    token: ({ token }) => token,
  },
  mutations: {
    SET_USER_TOKEN (state, { token }) {
      state.token = token;
      localStorage.setItem('token', token);
    },
    SET_USERINFO (state, { userinfo }) {
      state.userinfo = userinfo;
    },
  },
  actions: {
    // 获取用户数据
    async getUserinfo ({ commit }) {
      // 通过token获取用户数据
      // 请求中带token就行
      try {
        const userinfo = await getUserInfo();
        commit('SET_USERINFO', { userinfo });
      } catch (err) {
        console.log(err.message);
        // alert(err.message);
      }
    },
    // 用户登录
    async userLogin ({ commit, dispatch }, { userinfo }) {
      try {
        const { token } = await userLogin({ ...userinfo });
        commit('SET_USER_TOKEN', { token });
        dispatch('getUserinfo');
      } catch (err) {
        alert(err.message);
      }
    },
    async userLogout ({ commit }) {
      // 发出用户注销请求 并且清空数据
      try {
        await userLogout();
        commit('SET_USERINFO', {});
        commit('SET_USER_TOKEN', '');
        localStorage.removeItem('token');
      } catch (err) {
        console.log(err);
      }
    },
  },
};
